const { getList, getDetail, newBlog, updateBlog, deleteBlog } = require("../control/blog")
const { SuccessModel, ErrorModel } = require("../model/resModel")

// 统一验证登录函数
const loginCheck = (req) => {
  if(!req.session.username) {
    return Promise.resolve(
      new ErrorModel("尚未登录")
    )
  }
}

const handleBlogRouter = (req, res) => {
  const method = req.method
  const url = req.url
  const path = url.split("?")[0]
  const id =req.query.id
  
  // 获取博客列表
  if (method === "GET" && path === "/api/blog/list") {
    let author = req.query.author
    const keyword = req.query.keyword
    const listData = getList(author, keyword)

    if(req.query.isadmin){
      // 验证登录
      const loginResult = loginCheck(req)
      if(loginResult) {
        return loginResult
      }
      // 查询自己的博客
      author = req.session.username
    }

    return listData.then((result) => {
      return new SuccessModel(result)
    })
  }

  // 获取博客内容
  if (method === "GET" && path === "/api/blog/detail") {
    const detail = getDetail(id)
    return detail.then((detail) => {
      return new SuccessModel(detail)
    })
  }

  // 新增博客
  if (method === "POST" && path === "/api/blog/new") {

    // 验证登录
    const loginResult = loginCheck(req)
    if(loginResult) {
      return loginResult
    }

    const id = newBlog(req)
    return id.then(id => {
      return new SuccessModel(id)
    })
  }

  // 更新博客
  if (method === "POST" && path === "/api/blog/update") {
    // 验证登录
    const loginResult = loginCheck(req)
    if(loginResult) {
      return loginResult
    }

    const author = req.session.username
    const affectedRows = updateBlog(id, author, req.body)
    return affectedRows.then((affectedRows) => {
      if (affectedRows > 0) {
        return new SuccessModel("更新成功")
      } else {
        return new ErrorModel("更新失败")
      }
    })
  }

  // 删除博客
  if (method === "POST" && path === "/api/blog/del") {
    // 验证登录
    const loginResult = loginCheck(req)
    if(loginResult) {
      return loginResult
    }

    const author = req.session.username
    const affectedRows = deleteBlog(id, author)
    return affectedRows.then(affectedRows => {
      if (affectedRows > 0) {
        return new SuccessModel("删除成功")
      } else {
        return new ErrorModel("删除失败")
      }
    })
  }
}

module.exports = {
  handleBlogRouter
}
